package com.mrti.shop.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mrti.shop.pojo.Blog;
import com.mrti.shop.service.IBlogService;
import com.mrti.shop.util.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.Period;
import java.util.List;

@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private IBlogService blogService;

    @PostMapping("/modifyBlog")
    @ApiOperation(value = "修改博文")
    public R modifyBlog(@RequestBody Blog blog)
    {
        LocalDateTime modifyTime = LocalDateTime.now();
        blog.setModifyTime(modifyTime);
        boolean flag = blogService.updateById(blog);
        if(flag)
        {
            return R.success("博文修改成功");
        }
        else
        {
            return R.error("博文修改失败");
        }
    }

    @PostMapping("/removeBlog")
    @ApiOperation(value="删除博文")
    public R removeBlog(@RequestBody Blog blog)
    {
        boolean flag = blogService.removeById(blog);
        if(flag)
        {
            return R.success("博文删除成功");
        }
        else
        {
            return R.error("博文删除失败");
        }
    }

    @PostMapping("queryBlog1")
    @ApiOperation(value="查询博文")
    public R queryBlog1(@RequestBody Blog blog)
    {
        LambdaQueryWrapper<Blog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Blog::getContent,blog.getContent());
        List<Blog> blogList = blogService.list(lambdaQueryWrapper);
        if(blogList.size() != 0)
        {
            return R.success("查询到该博文",blogList);
        }
        else
        {
            return R.error("没有查询到该博文");
        }
    }

    @PostMapping("queryBlog2")
    @ApiOperation("查询一周内发布的博文")
    public R queryBlog2(@RequestBody Blog blog)
    {
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime oneWeakAgo = currentTime.minus(Period.ofWeeks(1));

        LambdaQueryWrapper<Blog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(Blog::getPostTime,oneWeakAgo,currentTime);

        List<Blog> blogList = blogService.list(lambdaQueryWrapper);

        if(blogList.size() != 0)
        {
            return R.success("查询到一周内发布的博文",blogList);
        }
        else
        {
            return R.error("未查询到一周内的博文");
        }

    }




}
